<?php
class CSVHandler {
	var $Separator;		//
	var $DataFile;
	var $DataKey;
	var $HeaderData;	//
	var $ItemsList;	//
	var $Items_Count;
	var $color;

	function CSVHandler($Filename, $Separator, $KeyFieldName) {		//Constructor
		$this->DataFile=$Filename;
		$this->DataKey=$KeyFieldName;
		$this->Separator=$Separator;
		$this->color="#FFFFFF";
	}
	
	function ReadCSV() {			//read data into this->ItemsList and return it in an array 
		$this->Items_Count = 0;
		$this->ItemsList = array();
		$Item = array();
		$fp = fopen($this->DataFile, 'r');
		$this->HeaderData = fgetcsv($fp, 3000, $this->Separator);
		while ($DataLine = fgetcsv($fp, 3000, $this->Separator)) {
			for($i=0; $i<count($this->HeaderData); $i++){
				$Item[$this->HeaderData[$i]] = @$DataLine[$i];
			}
			array_push($this->ItemsList,$Item);
			$this->Items_Count++;
		}
		fclose($fp);
		return ($this->ItemsList);
	}
	
	function Select($needle,$column="all")	{			//get items in a sort of SQL Select query and return them in an array
		$this->ReadCSV();
		if($needle=="*") {
			$result=$this->ItemsList;
		} else {
			$result=array();
			if($column=="all") {
				while(list($key,$line)=each($this->ItemsList)) {
     				if (stristr(implode("",$line),$needle)) array_push($result,$line);
				}
			} else {
				while(list($key,$line)=each($this->ItemsList)) {
     				if (stristr($line[$column],$needle)) array_push($result,$line);
				}
			}
		}
		return ($result);
	}
	
	function GetValues($field) {		//Fetch all values of a specified field and return values in array
		$Data=$this->ReadCSV();
		$values=array();
		while(list($key,$val)=each($this->ItemsList)) {
    		if(!in_array($val[$field],$values)) array_push($values,$val[$field]);
		}
		sort($values);
		return $values;
	}
}
?>
